import { Table, Button, Upload, message, Popconfirm, Card } from 'antd';
import React, { useState, useEffect } from 'react';
import { TrainList, TrainUpload, DeleteFile } from "@/services/A10/TrainController";
import { ModelTrain } from "@/services/A10/ModelController";
import styles from './model.less';
import { UploadOutlined, WarningOutlined } from "@ant-design/icons";
import { getLoginUserUsingGET } from "@/services/a10_back/userController";
import { useModel } from 'umi';
const ExamplePage = () => {
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [loading, setLoading] = useState(false);
  const [juage, setJuage] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);

  const loadData = () => {
    getLoginUserUsingGET().then(resp => {
      const userid = resp.data.id;
      TrainList(userid).then(resp => {
        const data = resp.data;
        const total = data.length;
        setData(resp.data);
        setTotal(total);
      });
    })
    const columns = [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        colSpan:0,
        render:()=>{return {props:{colSpan:0}};}
      },
      {
        title: '训练文件列表',
        dataIndex: 'fileName',
        key: 'fileName',
      },
      {
        title: '文件大小',
        dataIndex: 'fileSize',
        key: 'fileSize',
      },
      {
        title: '训练',
        dataIndex: 'Download',
        key: 'Download',
        render: (text, record) => {
          return (
            <div>
              <Button type="primary" onClick={() => {
                handleTrainModel(record);
              }} className={styles.ButtonInfo} loading={juageId.includes(record.id)}>
                训练模型
              </Button>
            </div>
          );
        },
      },
      {
        title: '删除',
        key: 'Delete',
        dataIndex: 'Delete',
        render: (text, record) => {
          return (
            <Popconfirm
              title="确定要删除此文件吗?"
              onConfirm={() => handleDeleteFile(record)}
              icon={
                <WarningOutlined
                  style={{
                    color: 'red',
                  }}
                />
              }
            >
              <Button type="primary" danger className={styles.ButtonInfo}>删除文件</Button>
            </Popconfirm>
          );
        },
      }
    ];
    setColumns(columns);
  }


  const handleDeleteFile = (record) => {
    DeleteFile(record).then((resp) => {
      if (resp.data === "success") {
        message.success("删除文件成功");
      }
      loadData();
    });
  }

  const { add, juageId,remove } = useModel('juage', (ret) => ({
    add: ret.addToJuage,
    juageId: ret.juage,
    remove:ret.removeFromJuage
  }));

  useEffect(() => {
    if (juageId !== null) {
      setJuage(juage);
      loadData();
      console.log(juage);
    }
  }, [juageId]);

  const handleTrainModel = (record) => {
    setLoading(true);
    const trainName = record.fileName;
    const newJuage = [...juage, trainName];
    setJuage(newJuage);
    add(record.id);
    let updatedRecord;
    getLoginUserUsingGET().then(resp => {
      const id = resp.data.id;
      updatedRecord = { ...record, userId: id };
      ModelTrain(updatedRecord).then((resp) => {
        if (resp.data.data.fileName === record.fileName) {
          setLoading(false);
          setJuage(juage.slice(1));
          message.success(`模型训练完成,用时${resp.data.data.runtime}`);
        } else {
          message.error("模型训练失败");
        }
        remove(record.id);
      });
    });
  }

  const handleTrainUpload = (record, fileName) => {
    const key = 'uploadingMessage';
    message.open({
      key,
      type: 'loading',
      content: '文件上传中...',
      duration: 0
    });
    TrainUpload(record).then((resp) => {
      if (resp.data === "success") {
        loadData();
        message.open({
          key,
          type: 'success',
          content: `${fileName} 上传成功`,
          duration: 2,
        });
      } else {
        message.open({
          key,
          type: 'error',
          content: `${fileName} 上传失败`,
          duration: 2,
        });
      }
    });
  }

  const handleButtonClick = () => {
    setLoading(true);
  }

  const handleUpload = (info) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file.data);
    }
    if (info.file.status === 'done') {
      const formData = new FormData();
      formData.append('file', info.file.originFileObj, info.file.name);
      let userid;
      getLoginUserUsingGET().then(resp => {
        userid = resp.data.id
        formData.append("userid", userid);
        handleTrainUpload(formData, info.file.name);
      });
    } else if (info.file.status === 'error') {

    }

  }

  const pagination = {
    current: currentPage,
    pageSize,
    total,
    onChange: (page) => {
      setCurrentPage(page);
    },
  };

  useEffect(() => {
      loadData();
  }, []);

  return (
    <div className={styles.container}>
      <Card>
        <Upload showUploadList={false} onChange={handleUpload} multiple={true}>
          <Button icon={<UploadOutlined />} className={styles.train} type={"primary"}>上传训练文件</Button>
        </Upload>
        <Table columns={columns} dataSource={data} pagination={pagination} />
      </Card>
    </div>
  );
}

export default ExamplePage;
